package com.gateway.filter

import org.springframework.cloud.gateway.filter.GatewayFilterChain
import org.springframework.cloud.gateway.filter.GlobalFilter
import org.springframework.core.Ordered
import org.springframework.http.HttpHeaders
import org.springframework.http.HttpMethod
import org.springframework.stereotype.Component
import org.springframework.web.server.ServerWebExchange
import reactor.core.publisher.Mono

@Component
class CrossOriginFilter : GlobalFilter, Ordered {
    override fun filter(exchange: ServerWebExchange?, chain: GatewayFilterChain?): Mono<Void>? {
        val headers = exchange?.response?.headers
        headers?.add(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "*")
        headers?.add(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "${HttpMethod.GET.name},${HttpMethod.POST.name}")
        headers?.add(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")
        headers?.add(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, "*")
        headers?.add(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, "*")
        return chain?.filter(exchange)
    }

    override fun getOrder(): Int {
        return 0
    }
}
